﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Shared.Service.DataPermissions
{
    /// <summary>
    /// 部门权限数据范围
    /// </summary>
    public class DepartmentDataPermission : DataPermission<string, DepartmentDataPermission>
    {
        /// <summary>
        /// 没启用的
        /// </summary>
        public static DepartmentDataPermission Disable = new DepartmentDataPermission(DataPermissionState.Disable);

        /// <summary>
        /// 没启用的
        /// </summary>
        public static DepartmentDataPermission Null = new DepartmentDataPermission(DataPermissionState.Null);

        /// <summary>
        /// 是否是所有
        /// </summary>
        public static DepartmentDataPermission All = new DepartmentDataPermission(DataPermissionState.All);

        /// <summary>
        /// 
        /// </summary>
        /// <param name="state"></param>
        protected DepartmentDataPermission(DataPermissionState state) : base(state)
        {

        }

        /// <summary>
        /// 部门
        /// </summary>
        /// <param name="departmentIds"></param>
        public DepartmentDataPermission(string[] departmentIds)
            : base(departmentIds)
        {

        }

        /// <summary>
        /// 以当前数据权限为基础，产生一个新的数据权限，
        /// 考虑用户输入的权限 默认交集计算  TODO 带抽象出通用方法
        /// 注意： inputIds 必须由内容，否则会抛出参数空异常
        /// </summary>
        /// <param name="inputIds"></param>
        /// <param name="disableAs">DisableAs 处理方式</param>
        /// <returns></returns>
        public override DepartmentDataPermission GetInputDataPermission(string[] inputIds,
            DisableAs disableAs = DisableAs.All)
        {

            if (inputIds.IsNullOrEmpty())
            {
                return this;
            }

            switch (State)
            {
                case DataPermissionState.Disable:
                    return disableAs switch
                    {
                        DisableAs.All => new DepartmentDataPermission(inputIds),
                        _ => Null
                    };
                case DataPermissionState.Null:
                    return Null;
                case DataPermissionState.Normal:
                    var intersectIds = Ids.Intersect(inputIds).ToArray(); // 取交集
                    return intersectIds.Any() ? new DepartmentDataPermission(intersectIds) : Null;
                case DataPermissionState.All:
                    return new DepartmentDataPermission(inputIds);
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
    }
}
